package ru.incoremedia.gaeutils.servlet;

import com.google.appengine.api.datastore.Blob;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ru.incoremedia.gaeutils.action.TransactionalAction;
import ru.incoremedia.gaeutils.dao.DatastoreResourceDao;
import ru.incoremedia.gaeutils.model.BaseEntity;
import ru.incoremedia.gaeutils.model.DatastoreResource;

public class DatastoreResourceServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setDateHeader("Expires", System.currentTimeMillis());
        resp.setHeader("Cache-Control", "public, max-age=1");

        final long id = Long.parseLong(req.getParameter("id"));

        Blob blob = new TransactionalAction<Blob>() {
            @Override
            public Blob doInTransaction() {
                BaseEntity baseEntity = new DatastoreResourceDao().get(id);
                return (Blob)baseEntity.getProperty(DatastoreResource.Property.DATA);
            }
        }.execute();

        if(blob != null) {
            resp.getOutputStream().write(blob.getBytes());
        }
    }

}
